/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.utils;

import java.io.File;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author Cody Stoutenburg
 * 
 */
public class ExternalClassLoad {

	public static String toClassName(String filename) {
		return filename.split(".class")[0];
	}

	public static Class<?> getClass(File classDirectory, String className)
			throws ClassNotFoundException {
		URL[] allURls = new URL[1];
		Class<?> c = null;
		try {
			allURls[0] = classDirectory.toURI().toURL();
			// Create a new class loader with the directory
			ClassLoader loader = new URLClassLoader(allURls);

			c = loader.loadClass(className);
		} catch (MalformedURLException ex) {
			ExceptionTool.showError("", ex);
		}

		return c;
	}

	public static Boolean verifyClass(File classDirectory,
			Class<?> inheriteFrom, String className, Boolean acceptAbstract) {
		Boolean isValid = false;
		try {
			Class<?> c = getClass(classDirectory, className);
			if (isInherited(c, inheriteFrom)) {
				if (acceptAbstract) {
					isValid = true;
				} else if (!Modifier.isAbstract(c.getModifiers())) {
					isValid = true;
				}
			}
		} catch (ClassNotFoundException ex) {
			ExceptionTool.showError("", ex);
		}

		return isValid;
	}

	public static Boolean isInherited(Class<?> c, Class<?> herited) {
		Boolean isInherited = false;

		while (c != null && !isInherited) {
			if (herited.equals(c)) {
				isInherited = true;
			}
			c = c.getSuperclass();
		}

		return isInherited;
	}

}
